﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Actions;
using COFE.Core.Logger;
using COFE.Core;

namespace COFE.Data
{
    public class DBWorkEventLogger : DBEventLoggerBase<COFE.Data.WorkEvent, WorkEventArgs>
    {
        public override void DispatchEvent(object sender, EventArgs args)
        {
            if (args is WorkEventArgs)
                DispatchEvent(sender, (WorkEventArgs)args);
        }

        public override void DispatchEvent(object sender, WorkEventArgs args)
        {
            switch (args.WorkEventType)
            {
                case EventType.Started:
                case EventType.Finished:
                case EventType.Failed:
                    string userId =
                        COFEShared.CurrentUserProfile == null ?
                        COFEShared.AdminUserProfile.UserName :
                        COFEShared.CurrentUserProfile.UserName;

                    COFEDBShared.DBOperations.UpdateDatabase(
                        (context) =>
                        {
                            var workEvent = new COFE.Data.WorkEvent()
                            {
                                UserId = userId,
                                Sender = sender == null ? "" : sender.ToString(),
                                Time = DateTime.UtcNow,
                                Type = (int)args.WorkEventType,
                                Message = args.ToString(),
                                WorkId = args.ID
                                        
                            };
                            context.Events.AddObject(workEvent);
                            context.SaveChanges();
                        });
                    break;
            }

        }

        protected override IEventLog createEventArgs(COFE.Data.WorkEvent e)
        {
            if (!e.WorkReference.IsLoaded)
                e.WorkReference.Load();
            return new EventLog<WorkEventArgs>(e.EventId, e.Time, e.Sender, e.UserId,
                                       new WorkEventArgs(((WorkEvent)e).WorkId,
                                           e.Work.Description,
                                           (Core.EventType)e.Type,
                                           e.Message));
        }

    }
}
